<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 钱多多
 */
class QianduoduoController extends PayController{
    protected $config;

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);
        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>'024']);
        }

        //$product = M("Product")->where(["id"=> I("request.pay_bankcode","")])->find();
        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));
        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>'024']);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $return = $this->orderadd( $parameter );


        $data = array();

        switch($this->config['paytype']){
            //微信
            case 1:
                $data['pay_fs'] = 'weixin';
                break;
            //支付宝
            case 3:
                $data['pay_fs'] = 'alipay_h5';
                break;
            //qq
            case 8:
                $data['pay_fs'] = 'qq';
                break;
            //微信H5
            case 2:
                $data['pay_fs'] = 'weixin_h5';
                break;
            //支付宝H5
            case 4:
                $data['pay_fs'] = 'alipay_h5';
                break;
            //QQ H5
            case 10:
                $data['pay_fs'] = 'qq';
                //$data['pay_fs'] = 'qq_h5';
                break;
            //银联扫码
            case 11:
                $data['pay_fs'] = 'un_e';
                break;
            //网银
            case 5:
            case 6:
                if(isMobile()){
                    $data['pay_fs'] = 'b2c_q';
                    $data['pay_returnUrl'] = $return['callbackurl'];

                    $data['pay_bankName'] = $this->getBankName($product['code']);
                }else{
                    $data['pay_fs'] = 'b2c';
                    $data['pay_returnUrl'] = $return['callbackurl'];

                    $data['pay_bankName'] = $this->getBankName($product['code']);
                }

                break;
            //银联快捷
            case 13:
                $data['pay_fs'] = 'b2c_q';
                $data['pay_returnUrl'] = $return['callbackurl'];

                $data['pay_bankName'] = 'ICBC';
                break;
            //京东
            case 9:
                $data['pay_fs'] = 'jd';
                break;
            default:
                $this->showmessage('不支持此产品!',['code'=>'024-1']);
        }
        $data['pay_MerchantNo'] = $this->config['mch_id'];
        $data['pay_orderNo'] = $return['orderid'];
        $data['pay_Amount'] = $return['amount'];
        $data['pay_NotifyUrl'] = $return['notifyurl'];
        $data['pay_ewm'] = 'No';
        $data['tranType'] = '2';
        $data['pay_ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'] ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];


        $str = $data['pay_fs'].$this->config['appsecret'].$data['pay_orderNo'].$data['pay_Amount'].$data['pay_NotifyUrl'].$data['pay_ewm'].$this->config['signkey'];
        $data['sign'] = md5($str);

        $res = $origin = curl($this->config['gateway'], httpstr($data));

        //保存请求返回
        M("Order")->where([ 'pay_orderid'=>$return['orderid']])->save(["rd_return"=>$res,"request"=>json_encode($data)]);

        if(!$res){
			echo $origin; exit;
            $this->showmessage('获取的数据为空!',['code'=>'024']);
        }

        $res = json_decode($res, true);

        //echo '<pre/>'; print_r($res); exit;
        $code = $res['pay_Code'];
        if(!$code){
            if($res['pay_CodeMsg']){
                $this->showmessage($res['pay_CodeMsg'],['code'=>'024']);
            }
            $this->showmessage('获取二维码失败!',['code'=>'024']);
        }

        switch($this->config['paytype']){
            //微信
            case 1:
                //支付宝
            case 3:
                //qq
            case 8:
                if(isMobile()){
                    //header("location: {$code}"); exit;
                }
                break;
            //微信H5
            case 2:
                //支付宝H5
            case 4:
                //QQ H5
            case 10:
                if(isMobile()){
                    header("location: {$code}"); exit;
                }
                break;
            //网银
            case 5:
            case 6:
                header("location: {$code}"); exit;
                break;
            //网银快捷
            case 13:
				header("location: {$code}"); exit;
                break;
            //京东
            case 9:
                $data['pay_fs'] = 'jd';
                break;
            default:
                $this->showmessage('不支持此产品!',['code'=>'012']);
        }

        $paytype = transArr( C("PAYTYPES"), "id");
		
		$code = str_replace(array("\n","\r\n"),"",urldecode($code));
		//$code = urlencode($code);
		
		echo $code . '<br/>';
		echo '<pre>'; print_r($res); echo '</pre>';
		echo 5;

        $this->assign("title", $paytype[$this->config['paytype']]);
        $this->assign("return", $return);
        $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?data=".urlencode($code));
        $this->display("WeiXin/Pay");
    }

    //通知
    public function notifyurl(){
        file_put_contents("a.txt",var_export($_POST,true)."\r\n\r\n");
        file_put_contents("a.txt",var_export($_GET,true)."\r\n\r\n", FILE_APPEND);
        file_put_contents("a.txt", file_get_contents('php://input')."\r\n\r\n", FILE_APPEND);
        file_put_contents("a.txt", date("Y-m-d H:i:s",time())."\r\n\r\n", FILE_APPEND);

        $p = file_get_contents('php://input');

        //$p = '{"pay_MerchantNo":"56255298","pay_OrderNo":"201809121608559132417","pay_Amount":"20","pay_Cur":{"pay_bankIdcard":"","pay_Idcard":"","pay_bankName":"","pay_bankMobile":"","pay_PayTime":"","pay_ProtocolNo":""},"pay_Status":"100","pay_PayTime":"","pay_DealTime":"2018-09-1216:09:30","sign":"6a31bf49d4d3737bb0d83c99214a4ed3"}';

        if(!$p){
            exit("no_data");
        }

        $p = json_decode($p, true);
        /*
        Array
        (
            [pay_MerchantNo] => 56255298
            [pay_OrderNo] => 201809112001527490062
            [pay_Amount] => 50
            [pay_Cur] => 1
            [pay_Status] => 100
            [pay_PayTime] => 2018-09-1120:02:18
            [pay_DealTime] => 2018-09-1120:02:18
            [sign] => e9bff4678b3cd84773c622a109c4bd27
        )
        */

        $sign = $p['sign'];

        //获取订单信息
        $orderid = $p['pay_OrderNo'];
        $find = M("Order")->where(array("pay_orderid"=>$orderid))->find();
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(
            "server_return"=> file_get_contents('php://input'),
        ));

        //获取渠道信息
        $this->config = Channel::getInstance()->find(['code'=>'Qianduoduo']);
        if(!$this->config){
            $this->config = M("Channel")->where(array('code'=>'Qianduoduo'))->find();
        }

        if(!$this->config){
            exit("get_tongdao_fail");
        }

        if(!$p || empty($p)){
            exit("wrong");
        }

        if($p['pay_Status'] != 100){
            exit("pay_fail");
        }

        //echo '<pre/>'; print_r($find);
        //print_r($this->config);

        $rd_return = json_decode($find['rd_return'] ,true);

        //MerchantNo+ pay_OrderNo+ pay_Amount +key
        $str = $this->config['appsecret'].$p['pay_OrderNo'].$p['pay_Amount'].$this->config['signkey'];

        $sign2 = md5($str);

        if($sign != $sign2){
            echo 'sign_wrong';exit;
        }

        //处理支付
        $this->EditMoney($find['pay_orderid'],"Qianduoduo",0);

        //回调成功
        echo 'success'; exit;
    }

    public function callBackUrl(){
        echo '处理成功'; exit;
    }

    public function getBankName($code){
        $ret = '';

        //农业银行 ABC 建设银行 CCB 兴业银行 CIB 招商银行 CMB 民生银行 CMBC 华夏银行 HXB
        //工商银行 ICBC 上海银行 BOSH 中国银行 BOC 交通银行 COMM 上海浦东发展银行 SPDB 广东发展银行 GDB 平安银行 PINGAN 邮政储蓄 PSBC 上海农村商业银行 SHRCB 北京银行 BOB 广州商业银行 GZCB 光大银行 CEB 温州银行 BOWZ 中信银行 CNCB
        switch($code){
            //北京银行
            case 'BOB':
                $ret = 'BOB';
                break;
            //东亚银行
            case 'BEA':
                $ret = '';
                break;
            //中国工商银行
            case 'ICBC':
                $ret = 'ICBC';
                break;
            //光大银行
            case 'CEB':
                $ret='CEB';
                break;
            //广发银行
            case 'CGB':
                $ret='GDB';
                break;
            //华夏银行
            case 'HXB':
                $ret='HXB';
                break;
            //中国建设银行
            case 'CCB':
                $ret='CCB';
                break;
            //交通银行
            case 'BOCOM':
                $ret='COMM';
                break;
            //中国民生银行
            case 'CMBC':
                $ret='CMBC';
                break;
            //南京银行
            case 'NJCB':
                $ret='';
                break;
            //宁波银行
            case 'NBCB':
                $ret='';
                break;
            //中国农业银行
            case 'ABC':
                $ret='ABC';
                break;
            //平安银行
            case 'PAB':
                $ret='PINGAN';
                break;
            //上海银行
            case 'SHB':
                $ret='';
                break;
            //上海浦东发展银行
            case 'SPDB':
                $ret='SPDB';
                break;
            //深圳发展银行
            case 'SDB':
                $ret='';
                break;
            //兴业银行
            case 'CIB':
                $ret='CIB';
                break;
            //中国邮政储蓄银行
            case 'PSBS':
                $ret='PSBC';
                break;
            //招商银行
            case 'CMB':
                $ret='CMB';
                break;
            //浙商银行
            case 'CZB':
                $ret='';
                break;
            //中国银行
            case 'BOC':
                $ret='BOC';
                break;
            //中信银行
            case 'CTTIC':
                $ret='CNCB';
                break;
            default:
                $this->showmessage('暂不支持此银行卡!',['code'=>'024']);
        }
        if(!$ret){
            $this->showmessage('暂不支持此银行卡!',['code'=>'024']);
        }

        return $ret;
    }
}